import json

from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ViewSet, GenericViewSet, ModelViewSet
from rest_framework.response import Response

from book_drf.serializers import BooksSerialzier
from books.models import BookInfo


class BooksDRF(ViewSet):#只继承了APIview
    """
        获取所有图书和保存图书
    """

    def list(self, request):
        # 1、查询所有图书
        books = BookInfo.objects.all()

        # 2、返回图书数据
        ser = BooksSerialzier(books, many=True)  # []

        return Response(ser.data)


class BookDRFModelViewsetBookDRF(GenericViewSet):#继承自GenericAPIView
    """
        获取单一图书和修改删除
    """

    serializer_class = BooksSerialzier
    queryset = BookInfo.objects.all()

    def list(self, request):
        # 1、查询所有图书
        books = self.get_queryset()

        # 2、返回图书数据
        ser = self.get_serializer(books, many=True)

        return Response(ser.data)

    def create(self, request):
        # 1、获取数据
        data = request.data
        # 2、检验
        ser = self.get_serializer(data=data)
        ser.is_valid()
        # 3、保存
        ser.save()
        # 4、返回
        return Response(ser.data)

    def update(self, request, pk):
        # 1、获取更新对象
        book = self.get_object()
        # 2、获取数据
        data = request.data
        # 3、检验
        ser = self.get_serializer(book, data=data)
        ser.is_valid()
        # 4、更新
        ser.save()
        # 5、返回
        return Response(ser.data)

    def lastdata(self, request):
        book = BookInfo.objects.get(id=13)
        ser = self.get_serializer(book)
        return Response(ser.data)


class BookDRFModelViewset(ModelViewSet):
    """
        获取单一图书和修改删除
    """

    serializer_class = BooksSerialzier
    queryset = BookInfo.objects.all()
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]

    # @action(methods=['get'], detail=False)
    # def lastdata(self, request):
    #     book = BookInfo.objects.get(id=13)
    #     ser = self.get_serializer(book)
    #     return Response(ser.data)
    #
    # @action(methods=['get'], detail=True)
    # def lastdata111(self, request, pk):
    #     book = BookInfo.objects.get(id=13)
    #     ser = self.get_serializer(book)
    #     return Response(ser.data)
